package com.firsteapps.mobile.android.puzzle;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.firsteapps.mobile.android.puzzle.game.DrawView;
import com.firsteapps.mobile.android.puzzle.game.Helper;
import com.firsteapps.mobile.android.puzzle.game.Puzzle;
import com.firsteapps.mobile.android.puzzle.game.PuzzleInfo;
import com.firsteapps.mobile.android.puzzle.util.Consts;

public class SharePuzzle extends PostLoginBase {

	private ListView puzzlesList;
	private TextView puzzleSizeViewer, movesCountViewer, attemptsCountViewer, timeLimitViewer, autosolveViewer;
	private DrawView puzzlePreview;
	private ImageView shareCurrentPuzzle, winPrizes, preview;
	private LinearLayout selectPuzzlesLayout, puzzleViewerLayout;
	private boolean isPreviewOn = false;
	// private int currentItemPosition = -1;
	private boolean[] selectedPositions;
	private PuzzleInfo info = null;
	private String puzzleName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.share_puzzle);

		puzzleSizeViewer = (TextView) findViewById(R.id.puzzle_size_viewer);
		movesCountViewer = (TextView) findViewById(R.id.moves_count_viewer);
		attemptsCountViewer = (TextView) findViewById(R.id.attempts_count_viewer);
		timeLimitViewer = (TextView) findViewById(R.id.time_limit_viewer);
		autosolveViewer = (TextView) findViewById(R.id.autosolve_viewer);

		puzzlesList = (ListView) findViewById(R.id.created_puzzles_list);
		puzzlesList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

		puzzlePreview = (DrawView) findViewById(R.id.puzzleView);
		selectPuzzlesLayout = (LinearLayout) findViewById(R.id.share_puzzles_layout);
		puzzleViewerLayout = (LinearLayout) findViewById(R.id.puzzle_viewer_layout);

		String[] shareItems = Helper.getPuzzleFiles(SharePuzzle.this, Consts.FILE_TYPE_INFO,
				getWorkingSubDirectory(Consts.FOLDER_NAME_CREATED));
		selectedPositions = new boolean[shareItems == null ? 0 : shareItems.length];
		Helper.resetSelectedItem(selectedPositions);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item_puzzles, shareItems) {
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				if (convertView == null) {
					LayoutInflater inflater = (LayoutInflater) SharePuzzle.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					convertView = inflater.inflate(R.layout.list_item_puzzles, null);
				}

				ImageView selectionView = (ImageView) convertView.findViewById(R.id.puzzle_item_state);
				TextView nameView = (TextView) convertView.findViewById(R.id.puzzle_item_name);
				TextView dateView = (TextView) convertView.findViewById(R.id.puzzle_item_date);
				TextView autosolveView = (TextView) convertView.findViewById(R.id.puzzle_item_autosolvable);

				selectionView.setBackgroundResource(selectedPositions[position] ? R.drawable.puzzle_selected
						: R.drawable.puzzle_not_selected);
				String currentItem = getItem(position);
				String[] puzzleAttrs = currentItem.substring(currentItem.lastIndexOf("/") + 1).split(Consts.FILENAME_SPLITTER);
				nameView.setText(Helper.getUserName(getUserName()) + "_" + puzzleAttrs[0].substring(0, puzzleAttrs[0].indexOf(".")));
				String dateStr;
				if (puzzleAttrs.length > 1) {
					dateStr = puzzleAttrs[1];
					dateStr = dateStr.replaceFirst("_", "/");
					dateStr = dateStr.replaceFirst("_", "/");
					dateStr = dateStr.replaceFirst("_", " ");
					dateStr = dateStr.replaceFirst("_", ":");
					dateStr = dateStr.replaceFirst("_", ":");
				} else
					dateStr = "Not specified";
				dateView.setText(dateStr);
				autosolveView.setText(puzzleAttrs.length > 2 ? puzzleAttrs[2] : "Not specified");

				return convertView;
			}
		};

		puzzlesList.setOnItemClickListener(new OnItemClickListener() {
			@SuppressWarnings("unchecked")
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (!selectedPositions[position]) {
					Helper.resetSelectedItem(selectedPositions);
					selectedPositions[position] = true;
					// ImageView selectedPuzzle = (ImageView) view.findViewById(R.id.puzzle_item_state);
					// selectedPuzzle.setBackgroundResource(R.drawable.puzzle_selected);
					puzzleName = (String) parent.getItemAtPosition(position);
					info = Helper.loadCreatedPuzzle(SharePuzzle.this, puzzleName);

					if (info == null) {
						Helper.doMessageDialog(SharePuzzle.this, "Share Puzzle", "Unable to load selected puzzle");
					} else {
						puzzleSizeViewer.setText(info.getSize() + ":" + info.getSize());
						movesCountViewer.setText(info.getMoveCount() + (info.getMaxMoves() > 0 ? "/" + info.getMaxMoves() : ""));
						attemptsCountViewer.setText(info.getAttempts()
								+ (info.getMaxAttempts() > 0 ? "/" + info.getMaxAttempts() : ""));
						timeLimitViewer.setText(Helper.getElapsedTime(info.getElapsed())
								+ (info.getMaxTime() > 0 ? "/" + Helper.getElapsedTime(info.getMaxTime() * 1000) : ""));
						autosolveViewer.setText(info.isAutosolvable() ? "YES" : "NO");

						((ArrayAdapter<String>) parent.getAdapter()).notifyDataSetChanged();
						// currentItemPosition = position;
					}
				}
			}
		});
		puzzlesList.setAdapter(adapter);

		winPrizes = (ImageView) findViewById(R.id.sp_win_prizes);
		winPrizes.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

			}
		});

		shareCurrentPuzzle = (ImageView) findViewById(R.id.sp_share_puzzle);
		shareCurrentPuzzle.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				AlertDialog dialog = new AlertDialog.Builder(SharePuzzle.this).setTitle("Share Puzzle")
						.setMessage("Are you sure you want to share the puzzle?")
						.setPositiveButton(android.R.string.ok, new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								if (info == null) {
									Helper.doMessageDialog(SharePuzzle.this, "Share Puzzle", "No item is selected");
								} else {
									info.resetPuzzle();
									Helper.shareCurrentPuzzle(SharePuzzle.this, puzzleName, info);
								}
							}
						}).setNegativeButton(android.R.string.cancel, new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						}).create();
				dialog.show();
			}
		});

		preview = (ImageView) findViewById(R.id.sp_preview);
		preview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (isPreviewOn) {
					puzzleViewerLayout.setVisibility(View.GONE);
					selectPuzzlesLayout.setVisibility(View.VISIBLE);
					// winPrizes.setVisibility(View.GONE);
					// shareCurrentPuzzle.setVisibility(View.VISIBLE);
					isPreviewOn = !isPreviewOn;
				} else {
					int position = puzzlesList.getCheckedItemPosition();
					if (position < 0) {
						Helper.doMessageDialog(SharePuzzle.this, "Share Puzzle", "No item is selected");
					} else {
						String selectedPuzzle = puzzlesList.getItemAtPosition(position).toString();
						if (selectedPuzzle != null) {
							PuzzleInfo info = Helper.loadCreatedPuzzle(SharePuzzle.this, selectedPuzzle);
							if (info == null) {
								Helper.doMessageDialog(SharePuzzle.this, "Share Puzzle", "Unable to load selected puzzle");
							} else {
								// getMorePuzzles.setVisibility(View.VISIBLE);
								// playGame.setVisibility(View.GONE);
								selectPuzzlesLayout.setVisibility(View.GONE);
								puzzleViewerLayout.setVisibility(View.VISIBLE);

								info.setTilePositions(null);
								puzzlePreview.setPuzzleSize(info.getSize());
								Puzzle puzzle = new Puzzle(Helper.getBitmap(SharePuzzle.this, info.getFile()), info);
								puzzlePreview.setFocusable(false);
								puzzlePreview.setPuzzle(puzzle);

								isPreviewOn = !isPreviewOn;
							}
						}
					}
				}
			}
		});
	}
}
